<template>
  <!-- 查询区 -->
  <div class="search">
    <el-form inline :model="courseSearchModel" label-width="90" label-position="right" ref="courseSearchForm">
      <el-form-item label="课程名称:">
        <el-input v-model="courseSearchModel.name" placeholder="请输入课程名称"></el-input>
      </el-form-item>
      <el-form-item label="教练:">
        <el-input v-model="courseSearchModel.coach" placeholder="请输入教练"></el-input>
      </el-form-item>
      <el-form-item label="教室:">
        <el-input v-model="courseSearchModel.room" placeholder="请输入教室"></el-input>
      </el-form-item>
    </el-form>
  </div>

  <!-- 按钮区-->
  <div class="action">
    <el-button type="primary" :icon="CirclePlus" @click="add">新增课程</el-button>
    <el-button type="primary" :icon="Edit" @click="edit">修改课程</el-button>
    <el-button type="danger" :icon="Delete" @click="remove">删除课程</el-button>
    <el-button type="primary" :icon="Search" @click="search()">查询课程</el-button>
    <el-button type="primary" :icon="Refresh" @click="reset">重置</el-button>
  </div>



  <!-- 表格区-->
  <div class="grid">
    <el-table :data="courses" stripe border @row-click="tblRowclick" ref="tblRef">
      <el-table-column type="selection" width="55" align="center" fixed></el-table-column>
      <el-table-column prop="id" label="ID" fixed></el-table-column>

      <el-table-column label="头像" fixed>
        <template #default="scope">
          <div class="row-avatar" :style="'background-image: url('+(baseUrl+scope.row.avatar)+')'"></div>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="课程名称" width="300"></el-table-column>
      <el-table-column prop="coach" label="教练"></el-table-column>
      <el-table-column prop="room" label="教室"></el-table-column>
      <el-table-column prop="startTime" label="上课时间"></el-table-column>
      <el-table-column prop="duration" label="时长(分钟)"></el-table-column>
      <el-table-column prop="bookedCount" label="团课预约人数">
        <template #default="scope">
          <el-tag :type="getBookedCountTagType(scope.row)">
            {{ scope.row.bookedCount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="maxCapacity" label="最大人数"></el-table-column>
      <el-table-column label="预约情况" width="120">
        <template #default="scope">
          <el-progress
              :percentage="calculateBookingPercentage(scope.row)"
              :status="getProgressStatus(scope.row)"
              :show-text="true"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="160">
        <template v-slot="scope">
          <el-button type="primary" size="small" @click="showCourseDetail(scope.row.id)">课程总预约</el-button>
          <el-button type="danger" size="small" @click="remove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条-->
  <div class="pagination">
    <el-pagination
        v-model:current-page="coursePi.pageNo"
        v-model:page-size="coursePi.pageSize"
        :page-sizes="[10, 15, 20, 30,50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="coursePi.total"
        class="course-pi"
        @change="coursePichange"
    />
  </div>

  <!-- 1添加/修改对话框-->
  <el-dialog v-model="courseDlgShow" :title="courseDlgTitle"
             width="600" draggable align-center @close="courseDlgClose"
             :close-on-click-modal="false">
    <el-form :model="courseModel" :rules="courseRules" label-width="120px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="课程名称:" prop="name">
            <el-input v-model="courseModel.name"></el-input>
          </el-form-item>

          <el-form-item label="教练:" prop="coach">
            <el-input v-model="courseModel.coach"></el-input>
          </el-form-item>

          <el-form-item label="上课时间:" prop="startTime">
            <el-date-picker
                v-model="courseModel.startTime"
                type="datetime"
                placeholder="Pick a Date"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-upload class="avatar" action="/api/courses/avatar"
                     :on-success="avatarUploadSuccess" :show-file-list="false">
            <div class="img" v-if="courseModel.avatar"
                 :style="'background-image: url('+(baseUrl+courseModel.avatar)+')'"></div>
            <el-icon v-else class="icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-col>
      </el-row>

      <el-form-item label="教室:" prop="room">
        <el-input v-model="courseModel.room"></el-input>
      </el-form-item>

      <el-form-item label="课程时长:" prop="duration">
        <el-input v-model="courseModel.duration" placeholder="请输入上课时长">
          <template #append>分钟</template>
        </el-input>
      </el-form-item>

      <el-form-item label="最大人数:" prop="maxCapacity">
        <el-input v-model="courseModel.maxCapacity" placeholder="请输入课程最大人数"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="doSubmit">确定</el-button>
        <el-button @click="courseDlgShow = false">取消</el-button>
      </div>
    </template>
  </el-dialog>


<!--  2点击编辑查看预约的学生信息的对话框-->
  <el-dialog v-model="courseDetailDlgShow" title="课程详情" width="600" @close="resetCourseDetail">
    <div class="course-detail">
      <!-- 课程基本信息 -->
      <div class="section">
        <h4>课程信息</h4>
        <el-row>
          <el-col :span="12">课程名称：{{ courseDetail.name }}</el-col>
          <el-col :span="12">教练：{{ courseDetail.coach }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="12">房间：{{ courseDetail.room }}</el-col>
          <el-col :span="12">最大容量：{{ courseDetail.maxCapacity }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="12">总预约人数：{{ courseDetail.bookedCount }}</el-col>
          <el-col :span="12">时长：{{ courseDetail.duration }} 分钟</el-col>
        </el-row>
      </div>

      <!-- 预约会员列表 -->
      <div class="section">
        <h4>预约会员</h4>
        <el-table :data="courseDetail.members" border style="margin-top: 10px">
          <el-table-column prop="id" label="ID" width="80"/>
          <el-table-column prop="name" label="姓名" width="150"/>
          <el-table-column prop="phone" label="电话" width="150"/>

          <!-- 新增：操作列 -->
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="danger" size="small" @click="cancelReservation(scope.row)">取消预约</el-button>
            </template>
          </el-table-column>
          <!-- 新增：课程类型列 -->
          <el-table-column label="课程类型" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.courseType == 0" type="primary">团课</el-tag>
              <el-tag v-else type="success">私课</el-tag>
            </template>
          </el-table-column>        </el-table>
        <div v-if="courseDetail.members.length == 0" class="no-members">
          暂无会员预约
        </div>
      </div>
    </div>

    <template #footer>
      <div>
        <el-button @click="courseDetailDlgShow = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>



.avatar {
  width: 140px;
  height: 140px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  margin-left: 8px;
  display: flex;
}

.avatar .icon {
  font-size: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar .img {
  width: 140px;
  height: 140px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
}

.row-avatar {
  width: 60px;
  height: 60px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
  border: 1px solid #ccc;
}
</style>

<style>
.el-upload {
  width: 100%;
}
</style>

<script setup>
import {ref, onMounted, reactive, toRaw, nextTick} from 'vue'
import api from '@/util/api'
import baseUrl from "@/util/constant.js";
import {CirclePlus, Delete, Edit, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";
import { useCourseStore } from '@/store/index.js';
import Calendar from './Calendar.vue'
const courseStore = useCourseStore();
let courseDetailDlgShow=ref(false)
let courseDetail=reactive({
  id: null,
  name: null,
  coach: null,
  room: null,
  maxCapacity: 0,
  bookedCount: 0,
  duration: 0,
  members:[],
  courseType:0
})
// 取消预约
async function cancelReservation(member) {
  console.log(member)
  ElMessageBox.confirm(`是否确认取消 ${member.name} 的预约?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    // 调用后端接口取消预约
    let resp = await api({
      url: `/reservations/cancel/${member.mcrId}`,
      method: "delete",
    });

    if (resp.success) {
      ElMessage.success("取消预约成功");

      // 从会员列表中移除该学生
      courseDetail.members = courseDetail.members.filter(m => m.id !== member.id);

      // 更新已预约人数
      courseDetail.bookedCount -= 1;

      // 同时更新主表格中的对应课程数据
      const course = courses.value.find(c => c.id === courseDetail.id);
      if (course) {
        course.bookedCount = courseDetail.bookedCount;
      }
    } else {
      ElMessage.error(resp.msg || "取消预约失败");
    }
  }).catch(() => {
    // 用户取消
  });
}


// 打开课程详情对话框
async function showCourseDetail(courseId) {
  courseDetailDlgShow.value = true;

  // 调用后端接口获取课程详情
  let resp = await api({
    url: `/courses/${courseId}`,
    method: "get"
  });

  if (resp.success) {
    courseDetail.id = resp.data.id;
    courseDetail.name = resp.data.name;
    courseDetail.coach = resp.data.coach;
    courseDetail.room = resp.data.room;
    courseDetail.maxCapacity = resp.data.maxCapacity;
    courseDetail.bookedCount = resp.data.bookedCount;
    courseDetail.duration = resp.data.duration;
    //存储下  预约记录ID
    courseDetail.members = (resp.data.members || []).map(member=>({
      id: member.id,
      name: member.name,
      phone: member.phone,
      mcrId: member.mcrId,
      courseType: member.courseType
    }));

    // 同时更新主表格中的对应课程数据，确保数据一致性
    // const course = courses.value.find(c => c.id === courseId);
    // if (course) {
    //   course.bookedCount = resp.data.bookedCount;
    //   course.maxCapacity = resp.data.maxCapacity;
    // }
  } else {
    ElMessage.error("获取课程详情失败");
  }
}


let courseDlgTitle = ref("新增课程");
let courseDlgShow = ref(false)
//查询全部课程
let courses = ref([])
let coursePi = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})
let courseSearchModel = ref({
  name: null,
  coach: null,
  room: null,

})
//新增课程表单
let courseModel = ref({
  name: null,
  coach: null,
  room: null,
  startTime: null,
  duration: null,
  maxCapacity: null,
  avatar: null
})
//表格对象：作用选中行、删除
let tblRef = ref()
//课程表格行点击
function tblRowclick(row) {
  tblRef.value.toggleRowSelection(row)
}
//查询
function coursePichange(pageNo, pageSize) {
  search(pageNo, pageSize)
}
function  resetCourseDetail(){
  courseDetail.id = null;
  courseDetail.name = null;
  courseDetail.coach = null;
  courseDetail.room = null;
  courseDetail.maxCapacity = 0;
  courseDetail.bookedCount = 0;
  courseDetail.duration = 0;
  courseDetail.members =[]
}
//重置课程表单
function courseDlgClose() {
  courseModel.value = {
    name: null,
    coach: null,
    room: null,
    startTime: null,
    duration: null,
    maxCapacity: null,
    avatar: null
  };
}
//重置查询条件
function reset() {
  courseSearchModel.value = {
    name: null,
    coach: null,
    room: null
  }
  search()
}
//删除课程
function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选中您要删除的行")
  } else {
    ElMessageBox.confirm("是否确认删除选中的课程?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      let ids = rows.map(it => it.id);
      removeByIds(ids);
    })
  }
}

async function removeByIds(ids) {
  let resp = await api({
    url: "/courses",
    method: "delete",
    data: ids
  })
  if (resp.success) {
    ElMessage.success("删除课程成功")
    search()
  } else {
    ElMessage.error("删除课程失败")
  }
}
async function search(pageNo = 1, pageSize = 10) {
  let params = toRaw(courseSearchModel.value);
  let resp = await api({
    url: "/courses",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params
    }
  })
  console.log("111")
  console.log(resp.data.records)
  courses.value = resp.data.records
  coursePi.pageNo = resp.data.current
  coursePi.pageSize = resp.data.size
  coursePi.total = resp.data.total


  // 将课程数据存储到 Pinia Store 中
  courseStore.setCourses(resp.data.records);
  console.log('课程数据已存储到 Store:', resp.data.records);
}

onMounted(() => {
  search()
})

/////////////////新增///////////////////////////////
function doSubmit() {
  if (mode === "add") {
    submitAdd()
  } else {
    submitEdit()
  }
}

let mode = "add"

function add() {
  mode = "add";
  courseDlgShow.value = true;
  courseDlgTitle.value = "添加课程";
}

function submitAdd() {
  let params = toRaw(courseModel.value);

  api({
    url: "/courses",
    method: "post",
    data: params
  }).then(resp => {
    if (resp.success) {
      ElMessage.success("保存成功")
      courseDlgShow.value = false;
      search();
    } else {
      ElMessage.error("保存失败")
    }
  })
}

function edit() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选中您要修改的行")
  } else if (rows.length > 1) {
    ElMessage.warning("只能选中一行")
  } else {
    mode = "edit";
    courseDlgShow.value = true;
    courseDlgTitle.value = "修改课程";
    //在下一个时间滴答中操作:数据回显
    nextTick(() => {
      //深度克隆
      courseModel.value = cloneDeep(toRaw(rows[0]));
    });
  }
}

function submitEdit() {
  let params = toRaw(courseModel.value);

  api({
    url: "/courses",
    method: "put",
    data: params
  }).then(resp => {
    if (resp.success) {
      ElMessage.success("修改成功")
      courseDlgShow.value = false;
      search();
    } else {
      ElMessage.error("修改失败")
    }
  })
}

//////////定义表单验证规则///校验////
const courseRules = {
  name: [
    {required: true, message: '请输入课程名称', trigger: 'blur'}
  ],
  room: [
    {required: true, message: '请输入教室名称', trigger: 'blur'}
  ],
  coach: [
    {required: true, message: '请输入教练姓名', trigger: 'blur'}
  ],
  startTime: [
    {required: true, message: '请选择上课时间', trigger: 'change'}
  ],
  duration: [
    {required: true, message: '请输入课程时长', trigger: 'blur'},
    {pattern: /^\d+$/, message: '时长必须为数字', trigger: 'blur'}
  ],
  maxCapacity: [
    {required: true, message: '请输入最大人数', trigger: 'blur'},
    {pattern: /^\d+$/, message: '最大人数必须为数字', trigger: 'blur'}
  ]
}

//头像上传
function avatarUploadSuccess(resp) {
  courseModel.value.avatar = resp.data;
}

// 计算预约百分比
function calculateBookingPercentage(course) {
  if (!course.maxCapacity || course.maxCapacity <= 0) {
    return 0;
  }
  return Math.round((course.bookedCount / course.maxCapacity) * 100);
}

// 获取进度条状态
function getProgressStatus(course) {
  const percentage = calculateBookingPercentage(course);
  if (percentage >= 90) {
    return 'exception'; // 红色
  } else if (percentage >= 70) {
    return 'warning'; // 黄色
  } else {
    return undefined; // 蓝色
  }
}

// 获取预约人数标签类型
function getBookedCountTagType(course) {
  const percentage = calculateBookingPercentage(course);
  if (percentage >= 90) {
    return 'danger'; // 红色
  } else if (percentage >= 70) {
    return 'warning'; // 橙色
  } else if (percentage >= 50) {
    return 'success'; // 绿色
  } else {
    return 'info'; // 灰色
  }
}
</script>
